package bankapplication.com.acme.networking;

import java.io.*;
import java.net.*;

import bankapplication.com.acme.bankapp.domain.bank.Bank;

public class BankServer {
  
  ServerSocket serversocket;
  Socket socket;
  BufferedReader in;
  BufferedWriter out;
  
  private String parseCommand(Bank bank, String command) {
    if(command.indexOf(' ') == -1){
      return "Bad command format"; 
    }
    String command_head = command.trim().substring(0,command.indexOf(' '));
    String command_body = command.trim().substring(command.indexOf(' ')+1, command.length()).trim();
    if(command_head.equals("add")){
      return BankReport.addClient(bank, command_body);
    }
    return "Command not found";
  }
  
  public void startServer(Bank bank) {
    try{
      try{
        serversocket = new ServerSocket(5432);
      }
      catch(IOException e){
        System.err.println("Не удаётся открыть серверный сокет.");
        return;
      }
      try{
        socket = serversocket.accept();
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
      }
      catch(IOException e){
        System.err.println("Не могу подсоединиться к созданному сокету.");
        return;
      }
      String command;
      try{
        do{
          command = in.readLine();
          out.write(parseCommand(bank, command));
        }while(!command.equals("quit"));
      }
      catch(IOException e){
        System.err.println("Аварийное завершение.");
        e.printStackTrace();
        return;
      }
    }
    finally{
      try{
        if(in != null){
          in.close();
        }
        if(out != null){
          out.close();
        }
        socket.close();
        serversocket.close();
      }
      catch(IOException e){
        System.err.println("Не могу корректно закрыть соединение.");
        e.printStackTrace();
      }
    }
  }
}
